import { defineStore } from "pinia";
import { getToken, removeToken, setToken } from "../utils/token-utils";
import type { UserInfoState } from "./interface";
// import { ElMessage } from 'element-plus'
import { reqLogin, reqUserInfo, reqLogout } from "@/api/user";
import { anyRoutes, allAsyncRoutes, staticRoutes } from "@/router/routes";
import router from "@/router";
import type { RouteRecordRaw } from "vue-router";
import { cloneDeep } from "lodash";

// 定义异步获取路由组件
function filterAsyncRouters(
  allAsyncRoutes: RouteRecordRaw[],
  routes: string[]
) {
  return allAsyncRoutes.filter((item) => {
    if (routes.includes(item.name as string)) {
      if (item.children && item.children.length > 0) {
        item.children = filterAsyncRouters(item.children, routes);
      }
      return true;
    }
  });
}

// 添加路由映射
const addRoutes = (routes: RouteRecordRaw[]) => {
  routes.forEach((item) => router.addRoute(item));
};

// 删除所有路由映射
const delRoutes = () => {
  const routes = router.getRoutes();
  routes.forEach((item) => {
    router.removeRoute(item.name!);
  });
  addRoutes(staticRoutes);
};

/**
 * 用户信息
 * @methods setUserInfos 设置用户信息
 */
export const useUserInfoStore = defineStore("userInfo", {
  state: (): UserInfoState => ({
    token: getToken() as string,
    userInfo: {
      routes: [],
      buttons: [],
      roles: [],
      name: "",
      avatar: "",
    },
    menuRoutes: [],
  }),

  actions: {
    async login(username: string, password: string) {
      try {
        const res = await reqLogin({ username, password });
        setToken(res.token);
        this.token = res.token;
      } catch (error) {
        return Promise.reject(error);
      }
      // return new Promise((resolve, reject) => {
      //   setTimeout(() => {
      //     if (username==='admin' && password==='111111') {
      //       const token = 'token-atguigu'
      //       setToken(token)
      //       this.token = token
      //       resolve(token)
      //     } else {
      //       reject(new Error('用户名或密码错误!'))
      //       ElMessage.error('用户名或密码错误!')
      //     }
      //   }, 1000)
      // })
    },

    // getInfo() {
    //   return new Promise((resolve, reject) => {
    //     setTimeout(() => {
    //       this.name = 'admin'
    //       this.avatar = 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif'
    //       this.menuRoutes = staticRoutes
    //       resolve({ name: this.name, avatar: this.avatar, token: this.token })
    //     }, 1000)
    //   })
    // },

    async getInfo() {
      try {
        const res = await reqUserInfo();
        this.userInfo = res;

        const filterRoutes = filterAsyncRouters(
          cloneDeep(allAsyncRoutes),
          res.routes
        );
        addRoutes(filterRoutes);
        addRoutes(anyRoutes);
        // console.log(filterRoutes);

        this.menuRoutes = [...staticRoutes, ...filterRoutes, ...anyRoutes];
      } catch (error) {
        return Promise.reject(error);
      }
    },
    async logout() {
      try {
        await reqLogout();
        this.reset();
      } catch (error) {
        return Promise.reject(error);
      }
    },
    reset() {
      // 删除local中保存的token
      removeToken();
      // 提交重置用户信息的mutation
      this.token = "";
      this.userInfo.name = "";
      this.userInfo.avatar = "";
      delRoutes();
    },
  },
});
